#include <stdlib.h>  /* atoi, malloc */
#include <string.h>  /* strcpy */
#include <math.h>

#include "devUsart.h"
#include "funcUart1.h"

extern struct buf_st g_stCom1Rbuf;
extern struct buf_st g_stCom1Tbuf;
extern unsigned char g_TxCom1Active;

void uart1_init (unsigned int uiBaudRate,
                unsigned short usWordLength,
                unsigned short usStopBits,
                unsigned short usParity,
                unsigned short usCtx) 
{
  uart1_dev_init( uiBaudRate, 
                  usWordLength, 
                  usStopBits, 
                  usParity, 
                  usCtx);
  
	USART_ITConfig(USART1, USART_IT_RXNE, DISABLE);
	USART_ITConfig(USART1, USART_IT_TXE, DISABLE);
	memset(&g_stCom1Rbuf, 0, sizeof(struct buf_st));
	
	memset(&g_stCom1Tbuf, 0, sizeof(struct buf_st));
	USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
	g_TxCom1Active = USART_FLASE;
}

int uart1_recv_char(void)
{
	int iCh = -1;
	struct buf_st *p = 0;
	p = &g_stCom1Rbuf;
	
	if(p->ucIn != p->ucOut){
		iCh  = p->ucBuf[p->ucOut++];
	}
	return iCh;	
}

int uart1_send_char(int iCh)
{
	int iRet = UART1_ERR;
  struct buf_st *p = &g_stCom1Tbuf;
	
	if ((unsigned char)(p->ucIn + 1) == p->ucOut) {
    return iRet;
  }

	p->ucBuf [p->ucIn++] = iCh;

	if ( USART_FLASE == g_TxCom1Active ) {
    g_TxCom1Active = USART_TRUE;
    USART_ITConfig(USART1, USART_IT_TXE, ENABLE);
  }
  iRet = iCh;
	return iRet;
}

int uart1_recv_data(unsigned char *pucBuf, unsigned short usSize)
{
	int iRet = UART1_ERR;
	unsigned char ucLen = 0;
	struct buf_st *p = 0;
	
	if(!pucBuf || 0 == usSize){
		return iRet;
	}
	p = &g_stCom1Rbuf;
	
	while(p->ucOut != p->ucIn){
		pucBuf[ucLen++] = p->ucBuf[p->ucOut++];
		if(ucLen == usSize){
			break;
		}
	}
	iRet = ucLen;

	return iRet;
}

int uart1_send_data(unsigned char *pucBuf, unsigned short usSize)
{
	unsigned short usPos = 0;
	
  struct buf_st *p = &g_stCom1Tbuf;

  if(!pucBuf || 0 == usSize){
		return UART1_ERR;
	}
  
	if ((unsigned char)(p->ucIn + 1) == p->ucOut) {
    return usPos;
  }
	while(usPos < usSize){
		p->ucBuf [p->ucIn++] = pucBuf[usPos++];
		if ((unsigned char)(p->ucIn + 1) == p->ucOut) {
	    break;
	  }
	}
	
	if ( USART_FLASE == g_TxCom1Active ) {
    g_TxCom1Active = USART_TRUE;
    USART_ITConfig(USART1, USART_IT_TXE, ENABLE);
  }

	return usPos;
}

